package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.lang.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            if (handlerMethod.hasMethodAnnotation(RequireLogin.class)) {
                String token = CookieUtil.getTokenByCookie(request);
                UserInfo userInfo = userInfoRedisService.getUserInfoByToken(token);
                //登录的时候已经把userinfo放在session中了
                if (userInfo == null) {
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        return true;
    }

}
